package com.yumeng.framework.runtime;

import com.yumeng.common.buss.area.AreaHelper;
import com.yumeng.common.buss.area.CurrSysAreaInfo;
import com.yumeng.common.data.enums.BaseEnum;
import com.yumeng.common.exception.YumengException;
import com.yumeng.common.helper.BaseEnumHelper;
import com.yumeng.common.runtime.SpringPropAdapter;
import com.yumeng.common.utils.ReflectUtils;
import com.yumeng.config.helper.RuntimeHelper;
import com.yumeng.config.properties.ProjectProperties;
import com.yumeng.config.properties.YumengAuthProperties;
import com.yumeng.config.properties.YumengBussProperties;
import com.yumeng.config.properties.YumengProperties;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author wxd
 * @date 2024/5/31 下午2:20
 */
@Slf4j
@Component
public class MyApplicationRunner implements ApplicationRunner {

    private final ProjectProperties projectProperties;
    private final YumengProperties yumengProperties;
    private final YumengBussProperties yumengBussProperties;
    private final YumengAuthProperties yumengAuthProperties;

    @Autowired
    public MyApplicationRunner(ProjectProperties projectProperties, YumengProperties yumengProperties, YumengBussProperties yumengBussProperties, YumengAuthProperties yumengAuthProperties){
        this.projectProperties = projectProperties;
        this.yumengProperties = yumengProperties;
        this.yumengBussProperties = yumengBussProperties;
        this.yumengAuthProperties = yumengAuthProperties;
    }

    @Override
    public void run(ApplicationArguments args) throws Exception {
        log.info("====================MyApplicationRunner开始执行");
        checkConfigInfo();
        initArea();
        initEnums();



        log.info("====================MyApplicationRunner执行结束");
    }


    /**
     * 简单验证配置文件是否符合约定规则
     * 最终文件格式 artifactId + sysFlag + envFlag + 具体模块（db,redis等）。如：
     * yumeng-webapp-default-dev
     * yumeng-webapp-default-cfg
     * yumeng-webapp-default-dev-db
     */
    private void checkConfigInfo(){
        log.info("验证配置文件加载是否正确......");
        String separator = "-";
        String artifactId = projectProperties.getArtifactId();
        String sysFlag = yumengProperties.getSysFlag();
        String envFlag = yumengProperties.getEnvFlag();
        String lastCfgName = yumengProperties.getLastCfgName();

        String firstActiveProfile = SpringPropAdapter.getFirstActiveProfile();
        if (!Objects.equals(envFlag, firstActiveProfile)){
            throw new YumengException("envFlag异常，【】-【】", envFlag, firstActiveProfile);
        }

        String prefix = (artifactId + separator + sysFlag).replaceAll("_", separator);
        String suffix = SpringPropAdapter.getLastActiveProfile();
        suffix = suffix != null ? suffix : SpringPropAdapter.getLastDefaultProfiles();
        suffix = suffix.replaceAll("_", separator);
        String targetCfgName = prefix + separator + suffix;
        if (!targetCfgName.equals(lastCfgName)){
            throw new YumengException("配置文件名称异常，【】-【】", lastCfgName, targetCfgName);
        }
    }

    /**
     * 地区初始化
     */
    private void initArea(){
        log.info("地区初始化......");
        CurrSysAreaInfo areaInfo = RuntimeHelper.getCurrSysAreaInfo(yumengBussProperties.getArea());
        AreaHelper.init(areaInfo);
    }

    /**
     * 枚举初始化
     *
     */
    private void initEnums(){
        log.info("预处理枚举类型......");
        List<String> baseEnumPackages = yumengProperties.getBaseEnumPackages();
        List<String> enumPackages = yumengProperties.getEnumPackages();

        Set<String> enumPkgSets = new HashSet<>();
        if (CollectionUtils.isNotEmpty(baseEnumPackages)){
            enumPkgSets.addAll(baseEnumPackages);
        }
        if (CollectionUtils.isNotEmpty(enumPackages)){
            enumPkgSets.addAll(enumPackages);
        }
        if (CollectionUtils.isEmpty(enumPkgSets)){
            throw new YumengException("未配置枚举路径");
        }
        Set<Class<? extends BaseEnum>> set = new HashSet<>();
        for (String pkg : enumPkgSets){
            set.addAll(ReflectUtils.getClasses(pkg, BaseEnum.class, true));
        }
        if (CollectionUtils.isEmpty(set)) {
            log.info("enums:[]");
            return;
        }
        // 循环获取BaseEnum枚举
        for (Class<? extends BaseEnum> clazz : set) {
            BaseEnum[] enumConstants = clazz.getEnumConstants();
            Map<Integer, BaseEnum> enumMap = new ConcurrentHashMap<>(enumConstants.length);
            for (BaseEnum baseEnum : enumConstants) {
                Integer code = baseEnum.getCode();
                enumMap.put(code, baseEnum);
            }
            // 设置map
            BaseEnumHelper.getBaseEnumMap().put(clazz.getName(), enumMap);
        }
        log.info("enums:{}", BaseEnumHelper.getBaseEnumMap());
    }
}
